package net.atomarrow.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import net.atomarrow.ioc.ActionContext;

public class FreemarkUtil {

    /**
     * 渲染模板
     * @param templateName
     * @param map
     * @return
     */
    public static  String render(String templateName,Map map) {
        Configuration cfg = new Configuration();
        cfg.setNumberFormat("0.##");
        cfg.setDefaultEncoding("UTF-8"); 
        HttpServletRequest request = ActionContext.getContext().getRequest();
        cfg.setServletContextForTemplateLoading(request.getServletContext(), "/WEB-INF/ftls");
        try {
            Template t = cfg.getTemplate(templateName+".ftl","UTF-8");
            StringWriter sw = new  StringWriter();
            t.process(map, sw); 
            return sw.toString();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
        
    }
    /**
     * 渲染模板
     * @param templateName
     * @param map
     * @return
     */
    public static  String render(String templateName,Object... params) {
        Configuration cfg = new Configuration();
        cfg.setNumberFormat("0.##");
        cfg.setDefaultEncoding("UTF-8"); 
        HttpServletRequest request = ActionContext.getContext().getRequest();
        cfg.setServletContextForTemplateLoading(request.getServletContext(), "/WEB-INF/ftls");
        try {
            Template t = cfg.getTemplate(templateName+".ftl","UTF-8");
            StringWriter sw = new  StringWriter();
            Map map = new HashMap();
            if(params.length%2!=0){
                new RuntimeException("参数个数必须为偶数个");
            }
            for(int i=0;i<params.length;i++){
                map.put(params[i], params[i+1]);
                i++;
            }
            t.process(map, sw); 
            return sw.toString();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
    
}
